//
//  LSYTopMsgView.m
//  TTClub
//
//  Created by RoyLei on 15/8/5.
//  Copyright (c) 2015年 TTClub. All rights reserved.
//

#import "LSYTopMsgView.h"
#import "AppDelegate.h"

static LSYTopMsgView *_topMsgView = nil;


@interface LSYTopMsgView ()
{
    
    UIView        *_statuaView;
    CGFloat        _height;
    CGFloat        _width;
}


@property (assign, nonatomic) BOOL shouldRemoveMyself;
@property (strong, nonatomic) NSTimer *timer;
@property (strong, nonatomic) UITapGestureRecognizer *tapGesture;

- (void)_showMsg:(NSString*)msg time:(NSTimeInterval)time state:(LSYTopMsgViewStatusBarType)statusBarType;
- (void)setAnimationDidStopSelector;

@end

@implementation LSYTopMsgView

+ (instancetype)sharedInstance
{
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] initWithFrame:[UIApplication sharedApplication].statusBarFrame];
        UIView *statusBar = [[UIApplication sharedApplication] valueForKey:@"statusBar"];
        [statusBar addSubview:sharedInstance];
    });
    return sharedInstance;
}

+ (void)showMassage:(NSString*)msg time:(NSTimeInterval)time state:(LSYTopMsgViewStatusBarType)statusBarType {
    
    [[self sharedInstance] _showMsg:msg time:time state:statusBarType];
}

+ (void)dissmissWithAnimationed:(BOOL)animationed {
    [[self sharedInstance] dissmissWithAnimationed:animationed];
}

+ (LSYTopMsgView *)showMassage:(NSString*)msg
                          time:(NSTimeInterval)time
                         state:(LSYTopMsgViewStatusBarType )statusBarType
                   tappedBlock:(TTClubNoParamsBlock )notificationTappedBlock {
    
    UIView *statusBar = [[UIApplication sharedApplication] valueForKey:@"statusBar"];
    LSYTopMsgView *topMsgView = [[LSYTopMsgView alloc] initWithFrame:[UIApplication sharedApplication].statusBarFrame];
    topMsgView.notificationTappedBlock = notificationTappedBlock;
    topMsgView.shouldRemoveMyself = YES;
    [topMsgView.tapGesture setEnabled:YES];
    [statusBar addSubview:topMsgView];
    [topMsgView _showMsg:msg time:time state:statusBarType];
    
    return topMsgView;
}

- (id)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        self.hidden = YES;
        [self setBackgroundColor:[UIColor clearColor]];
        
        CGSize size = [[UIScreen mainScreen] bounds].size;
        
        if (size.height > size.width) {
            
            _height = size.height;
            _width = size.width;
            
        }else {
            _height = size.width;
            _width = size.height;
        }
        
        _statuaView = [[UIView alloc] initWithFrame:self.bounds];
        [_statuaView setBackgroundColor:[UIColor clearColor]];
        _msgLable = [[UILabel alloc] initWithFrame:CGRectZero];
        [_msgLable setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
        [_msgLable setBackgroundColor:[UIColor clearColor]];
        [_msgLable setTextAlignment:NSTextAlignmentCenter];
        [_msgLable setTextColor:[UIColor whiteColor]];
        [_msgLable setFont:[UIFont fontWithName:_msgLable.font.fontName size:14]];
        
        [_statuaView addSubview:_msgLable];
        [self addSubview:_statuaView];
        
        _msgLable.sd_layout
        .leftEqualToView(self)
        .rightEqualToView(self)
        .bottomSpaceToView(self, 20)
        .heightIs(40);
        
        

        
        [self changeStatusBarOrientation];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeStatusBarOrientation) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    }
    
    return self;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Getter

- (UITapGestureRecognizer *)tapGesture
{
    if (!_tapGesture) {
        _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandelAction:)];
        [_tapGesture setEnabled:NO];
        [self addGestureRecognizer:_tapGesture];
    }
    
    return _tapGesture;
}

#pragma mark - changeStatusBarOrientation
//方向确定
- (void)changeStatusBarOrientation {
    
    UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    [_statuaView setAlpha:0];

    CGFloat heigth = STATUEHEIGHT;
    
    if (interfaceOrientation == UIInterfaceOrientationPortrait) {
        self.frame = CGRectMake(0, 0, _width, heigth);
        [_statuaView setTransform:CGAffineTransformMakeRotation(0)];
    }
    else if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
        
        self.frame = CGRectMake(0, _height - 20, _width, heigth);
        [_statuaView setTransform:CGAffineTransformMakeRotation(M_PI)];
    }
    else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
        
        self.frame = CGRectMake(0, 0, 20, _height);
        [_statuaView setTransform:CGAffineTransformMakeRotation( -M_PI / 2.0)];
    }
    else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        
        self.frame = CGRectMake(_width - 20, 0, 20, _height);
        [_statuaView setTransform:CGAffineTransformMakeRotation( M_PI / 2.0)];
    }
    
    [_statuaView setFrame:self.bounds];
    
    [UIView animateWithDuration:0.05
                          delay:[UIApplication sharedApplication].statusBarOrientationAnimationDuration
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         [_statuaView setAlpha:0.9];
                     }
                     completion:NULL];
}

#pragma mark - animation

//隐藏动画结束
- (void)setAnimationDidStopSelector {
    
    self.hidden = YES;
    if (self.shouldRemoveMyself) {
        [self removeFromSuperview];
    }
}

- (void)hiddenMsg {
    
    [self.timer invalidate];
    self.timer = nil;
    [UIView beginAnimations:@"hideMsgAnimation" context:nil];
    [UIView setAnimationDidStopSelector:@selector(setAnimationDidStopSelector)];
    [UIView setAnimationDuration:0.3f];
    [UIView setAnimationDelegate:self];
    
    CGRect rect = _msgLable.frame;
    rect.origin.y = -rect.size.height;
    [_msgLable setFrame:rect];
    
    [UIView commitAnimations];
}

- (void)dissmissWithAnimationed:(BOOL)animationed
{
    if (animationed) {
        [self hiddenMsg];
    }else{
        [self.timer invalidate];
        self.timer = nil;
        CGRect rect = _msgLable.frame;
		rect.origin.y = -rect.size.height;
        [_msgLable setFrame:rect];
        self.hidden = YES;
        
        if (self.shouldRemoveMyself) {
            [self removeFromSuperview];
        }
    }
}

- (void)_showMsg:(NSString*)msg time:(NSTimeInterval)time state:(LSYTopMsgViewStatusBarType)state {
    
    self.statusBarType = state;
    _msgLable.text = msg;
    switch (state) {
        case LSYTopMsgViewStatusBarTypeNomal:
            _msgLable.backgroundColor = colorWithHexAndAlpha(0x000000, 0.5);
            break;
        case LSYTopMsgViewStatusBarTypeWarning:
            _msgLable.backgroundColor = [UIColor colorWithRed:0.801 green:0.000 blue:0.000 alpha:0.900];
            break;
        default:
            break;
    }
    if (self.hidden) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(hiddenMsg) userInfo:nil repeats:NO];
        [self showStatusBarWithAnimation:YES];
    }else{
        [self.timer invalidate];
        self.timer = nil;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(hiddenMsg) userInfo:nil repeats:NO];
    }
}

- (void)showStatusBarWithAnimation:(BOOL)animationed
{
    if (animationed) {
        self.hidden = NO;
        CGRect rect = _msgLable.bounds;
        rect.origin.y = -rect.size.height;
        [_msgLable setFrame:rect];
        rect.origin.y = 0;
        //开始动画
        [UIView beginAnimations:@"showMsgAnimation" context:nil];
        [UIView setAnimationDuration:0.15f];
        [_msgLable setFrame:rect];
        [UIView commitAnimations];
    }else{
        self.hidden = NO;
        CGRect rect = _msgLable.bounds;
        rect.origin.y = 0;
    }
}

- (void)tapGestureHandelAction:(UITapGestureRecognizer *)tapGesture
{
    if (self.notificationTappedBlock) {
        self.notificationTappedBlock();
        [self dissmissWithAnimationed:YES];
    }
}

@end
